package com.example.erp.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * hutool工具类
 */
public class RSAUtils {
    // 从文件读取公钥
    public static String readPublicKey() {
        try (InputStream inputStream = RSAUtils.class.getClassLoader()
                .getResourceAsStream("keys/publicKey.key")) {
            if (inputStream == null) {
                throw new FileNotFoundException("PublicKey key file not found");
            }
            return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("Error reading private key", e);
        }
    }
    // 从文件读取私钥
    public static String readPrivateKey() {
        try (InputStream inputStream = RSAUtils.class.getClassLoader()
                .getResourceAsStream("keys/privateKey.key")) {
            if (inputStream == null) {
                throw new FileNotFoundException("Private key file not found");
            }
            return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new RuntimeException("Error reading private key", e);
        }
    }
    /**
     * 公钥加密
     * content 待加密内容
     * publicKey 公钥
     * @return 加密后的Base64字符串
     */
    public static String encrypt(String content) {
        RSA rsa = new RSA(null, readPublicKey());
        byte[] encrypted = rsa.encrypt(content.getBytes(), KeyType.PublicKey);
        return Base64.encode(encrypted);
    }
    /**
     * 私钥解密
     * encryptedContent Base64编码的加密内容
     * privateKey 私钥
     * @return 解密后的原文
     */
    public static String decrypt(String encryptedContent) {
        RSA rsa = new RSA(readPrivateKey(), null);
        byte[] decrypted = rsa.decrypt(Base64.decode(encryptedContent), KeyType.PrivateKey);
        return new String(decrypted);
    }
}
